<template>
	<view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				serveTime: 0,
				socketStatus: '', // Socket连接状态
			}
		},
		mounted() {
			this.initScokets()
		},
		methods: {
			// 判断是否已连接
			initScokets() {
				let that = this;
				// const token =""
				const userId = uni.getStorageSync('userId')
				uni.connectSocket({
					// 地址 根据自身填写
					url: `${this.wsUrl}/ai/socket/${userId}`,
					success(res) {
						that.open(); //1、判断是否打开连接
						that.scoketMessage(); //2、判断websocket服务器是否返回信息
						that.TimeOut(); //3、websocket超时操作
					},
					fail(err) {
						console.log("WebSocket连接失败 connectSocket=", err);
						that.error();
					},
				});
				// 监听关闭scoket
				uni.onSocketClose(function(res) {
					console.log('WebSocket 已关闭！669');
				});
			},
			//连接成功
			open() {
				let that = this;
				uni.onSocketOpen((res) => {
					console.log("WebSocket连接成功....");
					uni.setStorageSync('scoket',1)
					that.reset(); //连接成功之后做两秒的一次连接(心跳机制)
				});
			},
			//监听服务器返回信息
			scoketMessage() {
				let that = this;
				uni.onSocketMessage(function(res) {
					// console.log(res.data,'00000000')
					// console.log(JSON.parse(res.data))
					//获取服务器返回内容，并获取当前时间戳以作服务器超时判断
					if(res.data == '[DONE]'){
						that.$emit('onMessage', res.data)
					}else{
						that.$emit('onMessage', JSON.parse(res.data))
					}
					that.serveTime = new Date().getTime();
				});
			},
			//超时响应
			TimeOut() {
				let that = this;
				setInterval(function() {
					let times = new Date().getTime();
					if (times - that.serveTime > 2000) {
						//以下做超时后的操作
					}
				}, 500);
			},
			// 连接失败
			error() {
				let that = this;
				uni.onSocketError(function(res) {
					console.log("WebSocket连接打开失败，请检查！");
					that.initScokets(); //连接失败之后，重新向服务器发起连接
				});
			},
			// 心跳响应
			reset() {

				let that = this;
				clearInterval(that.timeoutObj);
				that.timeoutObj = setInterval(function() {
					//做一个判断：在没有获取某个值货值其他需求下，做个无响应的websocket连接。否则就                 做一个有响应的连接
					uni.sendSocketMessage({
						data: `PING`, //data值根据实际需求赋值
						success: (res) => {
							// console.log("正在发送....");
							console.log('心跳维持');
						},
						fail: (err) => {
							console.log("心跳维持失败,重新连接....");
							that.initScokets();
						},
					});
				}, 60000);
			},
			closeScoket(){
				// 页面销毁时关闭Socket连接
				uni.closeSocket()
				uni.setStorageSync('scoket',2)
			}
		},
		onUnload() {
			console.log(12)
			alert('2')
			// 页面销毁时关闭Socket连接
			uni.closeSocket()
		}
	}
</script>